<template>
  <div>
    <section v-show="!isUpload">
      <a-upload
        ref="uploadTemp"
        name="file"
        :action="action"
        :disabled="disabled"
        :fileList="fileList"
        @change="handleChange"
        :remove="removeFile"
      >
        <a-button :disabled="disabled">
          <a-icon type="upload" />附件
        </a-button>
      </a-upload>
    </section>
    <section v-show="isUpload">
      <a-tag closable v-model="tagShow" @close="handlerCloseTag">{{ data ? data.driverName : "" }}</a-tag>
    </section>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Emit, Vue } from "vue-property-decorator";
import { PREFIX } from "@/api/cfg";

@Component({ name: "UploadTemp" })
export default class UploadTemp extends Vue {
  @Prop({ type: Object }) data: any;
  private uploading: boolean = false;
  private disabled: boolean = false;
  private tagShow: boolean = true;
  private isUpload: boolean = false;
  public fileList: any = [];

  get action() {
    return `${PREFIX}/driver/huge`;
  }

  @Emit("remove")
  handlerCloseTag() {
    this.isUpload = false;
    this.tagShow = false;
  }

  @Emit("remove")
  removeFile(info: any) {
    this.disabled = false;
    this.fileList = [];
    this.uploadStatus(false);
    return true;
  }

  handleChange(info: any) {
    const fileList: any = info.fileList;
    const { response, name, size, status } = fileList[0];
    this.$emit("resetValid", ["filePath", "fileSize"]);
    if (status === "uploading") {
      const index = name.lastIndexOf(".");
      if (index == -1) {
        this.$message.warning("附件格式错误");
        return false;
      }
      const ext = name.substr(index + 1);
      const cache = ["exe", "dmg"];
      if (!cache.includes(ext)) {
        this.$message.warning("附件格式错误");
        return false;
      }

      const maxSize: number = 400 << 20;
      if (size >= maxSize) {
        this.$message.warning("附件大小不能超过400M");
        return false;
      }
      this.uploadStatus(true);
    }
    this.disabled = fileList.length > 0;
    if (status === "done") {
      const { errNo, item } = response;
      const { filePath } = item;
      if (errNo === 0) {
        this.uploadDone({
          filePath: filePath,
          fileSize: size
        });
      }
      this.uploadStatus(false);
    } else if (status === "error") {
      this.$message.error(`${info.file.name} file upload failed.`);
    }
    this.fileList = fileList;
  }

  @Emit("done")
  uploadDone(info: any): any {
    return info;
  }

  @Emit("uploading")
  uploadStatus(status: boolean) {
    this.uploading = status;
    return status;
  }

  initTemp(check: string) {
    this.uploading = false;
    this.disabled = false;
    this.tagShow = true;
    this.isUpload = check === "edit";
    this.fileList = [];
  }
}
</script>

<style lang="less" scoped>
</style>
